<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Admin\Manager;
use App\Libs\WeChatPublic;
use DB;
use Cache;
use Illuminate\Support\Facades\Redis;
use Illuminate\Foundation\Auth\ThrottlesLogins;

class PublicController extends Controller
{
    use ThrottlesLogins;
    protected $maxAttempts = 5;
    protected $decayMinutes = 1;
    private function SerialNumber($numary = [])
    {
        $num = [];
        $count = count($numary);
        sort($numary);
        if ($count > 1) {
            $temp = 0;
            for ($i = 0; $i < $count - 1; $i++) {
                if ($i === 0) {
                    $num[$temp][] = $numary[$i];
                }
                $j = $i + 1;
                $temp = $numary[$j] - $numary[$i] === 1 ? $temp : 1 - $temp;
                $num[$temp][] = $numary[$j];
            }
        }
        else {
            return $numary;
        }
        return $num;
    }

    public function test(Request $request)
    {
        $path = '';
        if ($request->isMethod('post')) {
            // dd($request->file('file'));
            $path = $request->file('file')->storeAs('public','test.xls');
            dd($path);
        }
        return view('admin.public.test',compact('path'));
    }

    public function test2(Request $request)
    {
        $post_data = [
            'grant_type' => 'client_credentials',
            'scope' => 'device_full_access'
        ];

        $url = "https://oauth.cleargrass.com/oauth2/token";
        $str_access_token = $this->send_post($url, $post_data);

        // $str_access_token = file_get_contents($url);
        $arr_access_token = json_decode($str_access_token, true);

        $access_token = $arr_access_token['access_token'];
        return $access_token;
    }


    //登录页面展示
    public function login()
    {
        if (auth('admin')->check()) {
            // The user is logged in...
            return redirect('/' . config('constant.name_admin') . '/index/index');
        }
        $name_rep = DB::table('setting')->where('id', '1')->value('name_rep');
        return view('admin.public.login', compact('name_rep'));
    }

    //标准版与专业版，功能比较
    public function compare()
    {
        return view('admin.public.compare');
    }

    //登录页面展示--微信
    public function loginByWeChat()
    {
         // phpinfo();die;
        if (auth('admin')->check()) {
            // The user is logged in...
            return redirect('/' . config('constant.name_admin') . '/index/index');
        }

        $wx = new WeChatPublic();
        $scene_str = 'login';
        // dd($wx->getIndustry());
        $info = $wx->getQrCodeInfo($scene_str, 120);
        // dd($info);
        $url = $info['url'];
        $ticket = $info['ticket'];

        $name_rep = DB::table('setting')->where('id', '1')->value('name_rep');
        return view('admin.public.loginByWeChat', compact('url', 'ticket', 'name_rep'));
    }

    //登录验证--微信
    public function checkWeChat(Request $request)
    {
        config(['cache.stores.file.path' => config('constant.cache_file_path')]); //在运行时修改配置
        $ticket = "T_{$request->ticket}";
        $value = Cache::get($ticket);
        // info(222222222222222222);
        // info(config('constant.cache_file_path'));
        // info($ticket);
        // info("value:".json_encode($value));
        if ($value) {
            # 验证通过
            Cache::forget($ticket); //删除该缓存

            // 通过 ID 认证用户
            auth('admin')->loginUsingId($value['login_id']);

            $this->loginLogJobDispatch(); //发送任务到队列--记录登录日志任务

            $result = 'true';
        }
        else {
            # code...
            $result = "false";
        }

        return $result;
    }

    //注册成功后跳转到此页面
    public function regSuccess()
    {
        return view('admin.public.regSuccess');
    }


    //注册
    public function reg(Request $request)
    {
        if ($request->isMethod('POST')) {
            //编写验证规则
            $arr = [
                'username' => 'required|unique:manager',
                'password' => 'required',
                'captcha' => 'required|captcha'
            ];
            //进行验证
            $request->validate($arr);
            //如果验证通过，继续向下执行...
            $data = $request->only(['username', 'password', 'gender', 'telephone', 'realname']);
            $data['password'] = bcrypt($data['password']); //laravel默认的bcrypt加密
            // $data['password'] = md5(env("MD5_SALT") . $data['password']);
            $result = Manager::insert($data);
            return $result ? '1' : '0';
        }
        else {
            return view('admin.public.reg');
        }
    }

    // 客户注册
    public function regClient(Request $request)
    {
        if ($request->isMethod('POST')) {
            //编写验证规则
            $arr = [
                'username' => 'required|unique:manager',
                'password' => 'required',
                'captcha' => 'required|captcha'
            ];
            //进行验证
            $request->validate($arr);
            //如果验证通过，继续向下执行...
            $data = $request->only(['username', 'password', 'client_name', 'client_addr', 'client_contact', 'client_tel']);
            $data['password'] = bcrypt($data['password']); //laravel默认的bcrypt加密
            $data['role_id'] = 50;
            $result = Manager::insert($data);
            return $result ? '1' : '0';
        }
        else {
            $name_rep = DB::table('setting')->where('id', '1')->value('name_rep');
            return view('admin.public.regClient', compact('name_rep'));
        }
    }

    //设置登录验证的字段
    public function username(){  
        return 'username';
    }

    //登录验证
    public function check(Request $request)
    {
        if (method_exists($this, 'hasTooManyLoginAttempts') &&
            $this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return "最多尝试5次/1分钟错误账号密码，请1分钟后再做尝试！！";
        }
        //编写验证规则
        $arr = [
            'username' => 'required',
            'password' => 'required',
            'captcha' => 'required|captcha'
        ];
        //进行验证
        $request->validate($arr);
        
        //如果验证通过，继续向下执行...
        //进行身份验证
        $data = $request->only(['username', 'password']);

        // $data['password'] = bcrypt($data['password']); //  bcrypt
        // $data['password'] = md5(env("MD5_SALT") . $data['password']);
        $data['status'] = '2'; //状态为启用
        $result = auth('admin')->attempt($data);
        // $2y$10$bGSY0Hr0QF3obM8LiaYiPepIhqeZZUfkeQGYlJzeXVfvwhe1NXu.O
        if ($result) {
            # 密码验证通过后，再验证下密码强度，密码弱就提示用户改密码再登录
            $pattern = '/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,30}$/';
            preg_match($pattern, $data['password'], $match);
            // $result = $match ? true : "系统检测到您的密码强度太弱，<br>请找管理员修改密码";
            if ($match) {
                # 通过正则验证
                $result = true;
            }
            else {
                # code...
                $result = "系统检测到您的密码强度太弱，<br>请找管理员修改密码";
                //删除用户信息
                auth('admin')->logout();
            }
        }
        else {
            # code...
            $result = '用户名或密码错误！';
            $this->incrementLoginAttempts($request);
        }


        if ($result === true) {
            # 认证通过
            if (config('constant.wechat_have')) {
                # 开通了微信公众号
                if ($open_id = auth('admin')->user()->open_id) {
                    # 该用户已绑定公众号，给用户发送模板消息
                    $data_login_notice_job['open_id'] = $open_id;
                    $data_login_notice_job['ip'] = \App\Libs\Helper::getClientIp();
                    $data_login_notice_job['username'] = auth('admin')->user()->username;
                    \App\Jobs\LoginNoticeJob::dispatch($data_login_notice_job); //发送任务到队列--登录成功通知任务
                }
            }
            /*更新remember_token 保证登录设备的唯一性 start*/
            DB::table('manager')->where('id',auth('admin')->user()->id)->update(['remember_token'=>csrf_token()]);
            /*更新remember_token 保证登录设备的唯一性 end*/
            $this->loginLogJobDispatch(); //发送任务到队列--记录登录日志任务
        }

        return $result === true ? 'true' : $result;
        // if ($result) {
        //     //身份验证通过，跳转到后台页面
        //     return redirect('/admin/index/index');
        // } else {
        //     //验证不通过，跳转回登录页面，并携带错误信息
        //     return redirect('/admin/public/login')->withErrors(['用户名或密码错误！']);
        // }
    }

    /* 发送任务到队列--记录登录日志任务 */
    private function loginLogJobDispatch()
    {
        $data_login_log_job['ip'] = \App\Libs\Helper::getClientIp();
        $data_login_log_job['manager_id'] = auth('admin')->user()->id;
        $data_login_log_job['realname'] = auth('admin')->user()->realname;
        \App\Jobs\LoginLogJob::dispatch($data_login_log_job); //发送任务到队列--记录登录日志任务
    }


    //仪器 -- 登录验证
    public function check2(Request $request)
    {
        dd($request->all());
        // $str = bin2hex($request->username);
        // return "000{$str}000";
        // return floatval("0x10");

        if ($request->isMethod('POST')) {
            $num = $request->username;
            $password2 = $request->password;

            $res = DB::table('manager')->where('num', $num)->where('password2', $password2)->first();
            if ($res) {
                # 验证通过
                return "start{1}end";
            }
            else {
                # 验证不通过
                return "start{0}end";
                // return $request->username . $request->password .'bbb';
            }
        }
        else {
            return view('admin.test');
        }
    }

    //退出登录
    public function logout()
    {   //删除用户信息
        auth('admin')->logout();
        //跳转到登录页面
        return redirect(route('loginAdmin'));
    }

    public function ieError()
    {
        return view('admin.public.ieError');
    }
}
